package utils;//package com.mika.music.utils;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class AutoTestUtils {
    public volatile static WebDriver driver;

    public static WebDriver createDriver() {
        if (driver == null) {
            synchronized (AutoTestUtils.class) {
                // 打开浏览器  使用驱动来打开
                WebDriverManager.chromedriver().setup();
                // 增加浏览器配置：创建驱动对象要强制指定允许所有访问链接
                ChromeOptions options = new ChromeOptions();
                options.addArguments("--remote-allow-origins=*");

                driver = new ChromeDriver(options);
                // 最大化窗口
                driver.manage().window().maximize();

                // 等待 2 秒
                driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(20));
            }
        }
        return driver;
    }

    public AutoTestUtils(String url) {
        // 调用 driver 对象
        driver = createDriver();
        // 访问URL
        driver.get(url);
    }

    // 截图功能
    public static void getScreenshot(String str) throws IOException {

        // 年月日 时分秒
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HH-mm-ss-SS");

        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());

        String fileName = "./src/test/image" + "/" + dirTime + "/" + str + "-" + fileTime + ".png";
//        System.out.println(fileName);
//        System.out.println("截图保存为：" + str);
        File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(srcFile, new File(fileName));
    }

    // 关闭浏览器
    public static void close() {
        driver.quit();
    }
    

}
